package com.fay.designPattern.oop.apiAuth;

import java.util.HashMap;
import java.util.Map;

/**
 * @Title:
 * @Description:
 * @Author Fay Wang
 * @Date 2022/3/1 14:06
 * @Version 1.0
 */
public class DefaultApiAuthenticatorImpl implements ApiAuthenticator {

    private CredentialStorage credentialStorage;

    public DefaultApiAuthenticatorImpl(CredentialStorage credentialStorage) {
        this.credentialStorage = credentialStorage;
    }

    @Override
    public void auth(String url) {
        ApiRequest apiRequest = ApiRequest.buildFromUrl(url);
        auth(apiRequest);
    }

    @Override
    public void auth(ApiRequest apiRequest) {
        String appId = apiRequest.getAppId();
        String token = apiRequest.getToken();
        long timestamp = apiRequest.getTimestamp();
        String originalUrl = apiRequest.getOriginalUrl();

        AuthToken clientAuthToken = new AuthToken(token, timestamp);
        if (clientAuthToken.isExpired()) {
            throw new RuntimeException("Token is expired");
        }

        String password = credentialStorage.getPasswordByAppId(appId);
        Map<String, String> params = new HashMap<>();
        params.put("appId", appId);
        params.put("password", password);
        AuthToken serverAuthToken = AuthToken.generate(originalUrl, System.currentTimeMillis(), params);
        if (!serverAuthToken.match(clientAuthToken)) {
            throw new RuntimeException("Token verification failed");
        }
    }
}
